<template>
  <div ref="chart" style="width: 100%; height: 100%;"></div>
</template>

<script>
import * as echarts from 'echarts'
import 'echarts-gl'
import elementResizeDetectorMaker from 'element-resize-detector'
import GlobalFilterListener from '../GlobalFilterListener.vue'
import { loadUnderEnterprise } from '@/api/enterprose'

const erd = elementResizeDetectorMaker()
const geoJSON = {
  3601: require('./3601.json'),
  360102: require('./360102.json'),
  360103: require('./360103.json'),
  360104: require('./360104.json'),
  360111: require('./360111.json'),
  360112: require('./360112.json'),
  360113: require('./360113.json'),
  360121: require('./360121.json'),
  360123: require('./360123.json'),
  360124: require('./360124.json'),
  // 经济技术开发区
  360190: require('./360111.json'),
  // 高新区
  360192: require('./360111.json'),
  // 湾里区
  360105: require('./360112.json')
}
const colors = {
  360102: '#af8956',
  360103: '#5a7cad',
  360104: '#d394c2',
  360111: '#7ccbc2',
  360112: '#baaf6c',
  360113: '#32766d',
  360121: '#b273a0',
  360123: '#517637',
  360124: '#3f562e',
}
export default {
  name: 'map-center',
  mixins: [GlobalFilterListener],
  data () {
    return {
      map: '3601',
      type: '1',
      typeValue: '-1',
      chart: null,
      option: {},
    }
  },
  computed: {
    themeColor () {
      return this.$store.state.user.theme
    },
    districts () {
      return this.$store.getters['user/districts']
    },
    enterpriseList () {
      return this.$store.state.energyEnterpriseList
    },
    barData () {
      const data = this.enterpriseList
      const type = this.type
      const typeValue = this.typeValue
      return data.filter(v => {
        if (type === '1') {
          return v.districtBelong === typeValue || typeValue === '-1'
        }
        return v.belongIndustry === typeValue || typeValue === '-1'
      }).map(v => ({
        name: v.name,
        value: [
          v.longitude,
          v.latitude,
          Math.random() + 0.5,
          v.name,
          v.id
        ]
      }))
    },
  },
  watch: {
    typeValue () {
      this.chart?.clear()
      this.renderMap()
    }
  },
  async mounted () {
    this.registerMaps()

    await this.getEnterprise()

    const chart = this.chart = echarts.init(this.$refs.chart)
    this.renderMap()

    this.bindClickRegionEvent()
    erd.listenTo(this.$refs.chart, function () {
      chart.resize({
        animation: {
          duration: 1000,
        }
      })
    })
  },
  beforeDestroy () {
    erd.removeAllListeners(this.$refs.chart)
    this.unbindClickRegionEvent()
  },
  methods: {
    bindClickRegionEvent () {
      if (this.chart) {
        this.chart.on('click', this.clickHandler)
      }
    },
    unbindClickRegionEvent () {
      if (this.chart) {
        this.chart.off('click', this.clickHandler)
      }
    },
    getEnterprise () {
      return new Promise((resolve) => {
        loadUnderEnterprise().then(res => {
          res.data = res.data || []
          resolve(res.data.map(v => ({
            name: v.enterpriseName,
            value: v.id,
            id: v.id,
            enterpriseId: v.id,
            longitude: v.longitude,
            latitude: v.latitude,
            districtBelong: v.districtBelong,
            districtBelongName: v.districtBelongName,
            belongIndustry: v.belongIndustry,
            belongIndustryName: v.belongIndustryName,
            position: [v.longitude, v.latitude],
          })))
        })
      })
    },
    registerMaps () {
      for (const map in geoJSON) {
        echarts.registerMap(map, geoJSON[map])
      }
    },
    eventBusHandler ({ type, typeValue }) {
      this.map = type === '1' ? (typeValue !== '-1' ? typeValue : '3601') : '3601'
      this.type = type
      this.typeValue = typeValue
    },
    getChartOption () {
      const data = this.barData
      const regions = geoJSON[this.map].features
      return {
        ...this.option,
        tooltip: {
          show: true,
          backgroundColor: 'transparent',
          borderColor: 'transparent',
          extraCssText: 'box-shadow: none;',
          formatter (params) {
            return `
              <div class="geo3d-tooltip">${params.data.name}</div>
            `
          }
        },
        geo3D: {
          type: 'map3D',
          map: this.map,
          boxHeight: 7,
          regionHeight: 2,
          itemStyle: {
            opacity: 0,
          },
          viewControl: {
            alpha: 15,
            autoRotate: true,
            center: [0, -10, 0]
          },
          emphasis: {
            label: {
              show: false,
            },
            itemStyle: {
              opacity: 1,
              color: 'rgb(14,131,216)'
            }
          },
          zlevel: 0,
        },
        series: [
          {
            type: 'map3D',
            map: this.map,
            boxHeight: 7,
            regionHeight: 2,
            viewControl: {
              alpha: 15,
              autoRotate: true,
              center: [0, -10, 0]
            },
            emphasis: {
              label: {
                show: false,
              },
            },
            // silent: true,
            data: regions.map(v => ({
              name: v.properties.name,
              value: v.properties.adcode,
              itemStyle: {
                color: colors[v.properties.adcode],
              },
            })),
            zlevel: 2,
          },
          {
            type: 'bar3D',
            coordinateSystem: 'geo3D',
            barSize: 1,
            itemStyle: {
              opacity: 1,
              color: '#f7ffff'
            },
            shading: 'realistic',
            realisticMaterial: {
              detailTexture: require('./wenli.png')
            },
            data: data,
            zlevel: 11
          },
        ]
      }
    },
    renderMap () {
      const option = this.option = this.getChartOption()
      this.chart?.setOption(option, true)
    },
    clickHandler (e) {
      let type
      const seriesType = e.seriesType
      let id
      if (seriesType === 'map3D') {
        id = e.value
        type = 'districtCode'
      } else if (seriesType === 'bar3D') {
        id = e.value[e.value.length - 1]
        type = 'enterpriseCode'
      }
      if (!id) return
      this.$router.push({
        name: 'EnterpriseAnalysis',
        query: {
          [type]: id,
        }
      })
    },
  }
}
</script>
